package cn.tedu.charging.device.dao.repository;

import cn.tedu.charging.common.pojo.po.ChargingStationPO;
import cn.tedu.charging.device.dao.mapper.ChargingStationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.domain.geo.GeoLocation;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StationRepository {
    @Autowired
    private ChargingStationMapper chargingStationMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<ChargingStationPO> findAll(){
        return chargingStationMapper.selectList(null);
    }

    public GeoResults<GeoLocation<Integer>> nearbyStations(Double longitude, Double latitude, Double radius) {
        if (longitude == null || latitude == null || radius == null) {
            throw new IllegalArgumentException("经度、纬度或半径不能为空");
        }
        Circle circle=new Circle(
                new Point(longitude,latitude),
                new Distance(radius, Metrics.KILOMETERS));
        RedisGeoCommands.GeoRadiusCommandArgs args=
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates();
        return redisTemplate.opsForGeo().radius("beijing_stations", circle, args);
    }

    public String getStationNameById(Integer stationId) {
        String stationKey="station:cache:"+stationId;
        ValueOperations<String,ChargingStationPO> opsFor= redisTemplate.opsForValue();
        ChargingStationPO stationPO=opsFor.get(stationKey);
        if(stationPO==null){
            throw new RuntimeException("缓存异常，请检查");
        }
        return stationPO.getStationName();
    }

    public ChargingStationPO getStationById(Integer stationId) {
        String stationKey="station:cache:"+stationId;
        ValueOperations<String,ChargingStationPO> opsFor= redisTemplate.opsForValue();
        ChargingStationPO stationPO=opsFor.get(stationKey);
        if(stationPO==null){
            throw new RuntimeException("缓存异常，请检查");
        }
        return stationPO;
    }
}
